//
//  BandConfigListModel.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/27.
//

import UIKit
import HandyJSON

open class BandConfigListModel: NSObject, HandyJSON {
    
    fileprivate static let userDefaultKey: String = "BandConfigListModel"
    
    /// 接口是否响应成功 code
    public var code: Int?
    
    /// 接口版本号
    public var v: Int?
    
    /// img base url
    public var url: String?
    
    /// 需要删除的config id
    public var deleted: [Int]?
    
    public var list: [BandConfigModel]?
    
    
    public required override init() {}
    
    
    
    
    public static func current() ->BandConfigListModel? {
        
        let dict = UserDefaults.standard.dictionary(forKey: Self.userDefaultKey)
        let model = BandConfigListModel.deserialize(from: dict)
        
        model?.list = BandConfigModel.all()
        
        return model
        
    }
    
    
    public func saveAll() {
        
        self.saveUserDefault()
        self.saveSQLiteModels()
        
    }
    
    public func deletedAll() {
        
        self.deletedSQLiteModels()
    }
    
    
    public func imageURL(with logo: String) ->String? {
        guard let url = url, let baseUrl = URL(string: url) else {
            return nil
        }
        let imageURL = URL(string: logo, relativeTo: baseUrl)?.absoluteString
        return imageURL
    }
    
    
}

fileprivate extension BandConfigListModel {
    
     func saveUserDefault() {
        
        guard var dict: [String: Any] = self.toJSON(), !dict.isEmpty else {
            return
        }
        if dict.keys.contains("list") {
            dict.removeValue(forKey: "list")
        }
        
        UserDefaults.standard.set(dict, forKey: Self.userDefaultKey)
        
    }
    
     func saveSQLiteModels() {
        
        guard let list = list, !list.isEmpty else {
            return
        }
         
        list.forEach {
            
            let logo = $0.logo.compactMap { path in self.imageURL(with: path) }
            $0.logo = logo
            $0.updateData()
        }
        
    }
    
     func deletedSQLiteModels() {
        
        guard let deleted = deleted, !deleted.isEmpty else {
            return
        }

        deleted.forEach { configId in
            
           let model = BandConfigModel.model(with: configId)
            model?.delete()
        }

    }
    
}
